package com.longteng.diamond.util;

import com.longteng.diamond.domain.ReportLog;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: taki
 * Date: 15-4-3
 * Time: 上午10:20
 * To change this template use File | Settings | File Templates.
 */

@Slf4j
public class ReportLogFileUtil {

   private static DateUtil dateUtil=new DateUtil();
    private File file;
    private FileInputStream reader;
    // 上次文件大小
    private long lastTimeFileSize = 0; 
    private OutputStreamWriter writer;
    private FileOutputStream fileOutputStream;
    private static String filePath = "d://";
    private Integer buildTestId;


    public ReportLogFileUtil(Integer buildTestId) {
//        file = new File(shareDir+Integer.toString(buildTestId) + ".log");
        this.buildTestId = buildTestId;
    }

    public ReportLogFileUtil() {
    }
    /**
     * 构造方法
     * @return
     */
    public ReportLogFileUtil(String filePath) {
        file = new File(filePath);
        log.debug("创建写入文件,文件路径:" + file.getAbsolutePath());
        try {
            fileOutputStream = new FileOutputStream(file, true);
            writer = new OutputStreamWriter(fileOutputStream, "UTF-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     * 删除文件
     * @return
     */
    public void deleteFile() {
        try {
            log.debug("删除当前文件路径:" + file.getAbsolutePath());
            if (file.exists()) {
                this.writer.close();
                this.fileOutputStream.close();
                this.file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
    /**
     * 写入文件
     * @param text
     * @return
     */
    public void writeRedSpan(String text) {
        try {
            writer.write("[" + dateUtil.getCurrentDate() + " ] --> <span style='color:#9F1F2E;'>" + text + "</span>\r\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     * 写入文件
     * @param text
     * @return
     */
    public void writeGreenSpan(String text) {
        try {
            writer.write("[" + dateUtil.getCurrentDate() + " ] --> <span style='color:green;'>" + text + "</span>\r\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     * 写入文件
     * @param text
     * @return
     */
    public void writeSpan(String text) {
        try {
            writer.write("[" + dateUtil.getCurrentDate() + " ] --> <span style='color:#5636C1;'>" + text + "</span>\r\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     * 写入文件
     * @param text
     * @return
     */
    public void write(String text) {
        try {
            writer.write("[" + dateUtil.getCurrentDate() + " ] --> " + text + "\r\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     * 根据最后一次读取的位置读取日志
     * @param filePath
     * @param lastTimeFileSize
     * @return
     */
    public ReportLog read(String filePath, long lastTimeFileSize) {
        ReportLog reportLog = new ReportLog();
        StringBuffer stringBuffer = new StringBuffer();
        RandomAccessFile randomFile=null;
        try {
//            File file1=new File(shareDir+this.buildTestId+".log");
            log.debug("实时读取文件内容,文件路径:" + filePath);
            randomFile = new RandomAccessFile(filePath, "r");
            randomFile.seek(lastTimeFileSize);
            String tmp = null;
            while ((tmp = randomFile.readLine()) != null) {
                String temp=new String(tmp.getBytes("ISO-8859-1"), "UTF-8");
                if(temp.contains("ERROR")){
                    stringBuffer.append("<div style=\"color:red;\">" + new String(tmp.getBytes("ISO-8859-1"), "UTF-8") + "</div>");
                }else{
                    stringBuffer.append("<div >" + new String(tmp.getBytes("ISO-8859-1"), "UTF-8") + "</div>");
                }

            }
            lastTimeFileSize = randomFile.length();
            reportLog.setLastTimeFileSize(lastTimeFileSize);
            reportLog.setStrReport(stringBuffer.toString());
        } catch (FileNotFoundException f) {
            log.error("未找到文件:"+filePath);
            reportLog.setLastTimeFileSize(lastTimeFileSize);
            reportLog.setStrReport("");
        } catch (IOException e) {
            log.error("getreadLog error:" + e.getMessage());
            reportLog.setLastTimeFileSize(lastTimeFileSize);
            reportLog.setStrReport("");
        }finally {
            try {
                if(null!=randomFile) {
                    randomFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return reportLog;
    }
    /**
     * 读取日志文件
     * @param oldFile
     * @return
     */
    public String readOld(File oldFile) {
        StringBuffer sb = new StringBuffer();
        try {
            List<String> resultList = new ArrayList<String>();
            log.debug("读取旧文件内容,文件路径:" + oldFile.getAbsolutePath());
            /**考虑到编码格式**/
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(oldFile), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                resultList.add(lineTxt);
            }
            bufferedReader.close();
            read.close();
            for (int i = 0; i < resultList.size(); i++) {
                sb.append("<div>" + resultList.get(i) + "</div>");
            }
        } catch (IOException e) {
            log.error("",e);
        }
        return sb.toString();
    }
    /**
     * 关闭writer
     * @return
     */
    public void closeWriter() {
        try {
            this.writer.close();
            this.fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
